package com.u.social.article.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.u.social.article.entity.ArticleFavorite;
import com.u.social.article.entity.ArticleStats;
import com.u.social.article.mapper.ArticleFavoriteMapper;
import com.u.social.article.service.IArticleFavoriteService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.u.social.article.service.IArticleStatsService;
import com.u.social.article.service.IRedisService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author Alex Wu
 * @since 2025-02-25
 */
@Slf4j
@Service
public class ArticleFavoriteServiceImpl extends ServiceImpl<ArticleFavoriteMapper, ArticleFavorite> implements IArticleFavoriteService {

    @Autowired
    private IRedisService redisService;

    @Autowired
    private IArticleStatsService articleStatsService;
    @Override
    public Boolean addArticleToFavorite(Long favoriteUserId, Long articleId, Long favoriteId, Integer status) {

        boolean isFavorite = Objects.equals(status, 1);

        if(isFavorite){
            redisService.incrementHash("article_favorite_count", articleId.toString(), 1);
        }else {
            Object articleLikeCount = redisService.getHash("article_favorite_count", articleId.toString());
            if(articleLikeCount != null && Integer.parseInt(articleLikeCount.toString()) > 0) {
                redisService.incrementHash("article_like_count", articleId.toString(), -1);
            }
        }
        String hashKey = favoriteUserId + ":" + articleId  + ":" + favoriteId;
        redisService.putHash("article_favorite_status", hashKey, status);
        return true;
    }


    /**
     * 定时任务，每隔1分钟执行一次，同步点赞状态到数据库
     */
    @Scheduled(fixedRate = 1000 * 60) // 每隔1分钟执行一次
    public void syncLikeStatus() {
        // 1. 批量同步点赞状态到数据库
        List<ArticleFavorite> articleFavoritesList = new ArrayList<>();

        redisService.getAllHash("article_favorite_status").forEach((k, v) -> {
            String[] keys = k.toString().split(":");
            Long userId = Long.parseLong(keys[0]);
            Long articleId = Long.parseLong(keys[1]);
            Long favoriteId = Long.parseLong(keys[2]);
            Integer status = Integer.parseInt(v.toString());

            ArticleFavorite articleFavorite = this.getOne(new QueryWrapper<ArticleFavorite>().eq("user_id", userId)
                    .eq("articleId", articleId));


            if(articleFavorite == null) {
                articleFavorite = new ArticleFavorite();
            }
            articleFavorite.setFavoriteUserId(userId);
            articleFavorite.setArticleId(articleId);
            articleFavorite.setFavoriteId(favoriteId);
            articleFavorite.setStatus(status);

            articleFavoritesList.add(articleFavorite);
        });

        if(!articleFavoritesList.isEmpty()){
            this.saveOrUpdateBatch(articleFavoritesList);
        }
        log.info("syncLikeStatus success: {}", articleFavoritesList);

        // 2. 批量同步点赞数量到数据库
        List<ArticleStats> articleStatsList = new ArrayList<>();
        redisService.getAllHash("article_favorite_count").forEach((k, v) -> {
            Long articleId = Long.parseLong(k.toString());
            Integer favoriteCount = Integer.parseInt(v.toString());

            ArticleStats articleStats  = articleStatsService.getOne(new QueryWrapper<ArticleStats>().eq("article_id", articleId));
            if(articleStats == null) {
                articleStats = new ArticleStats();
            }

            articleStats.setFavoriteCount(favoriteCount);
            articleStatsList.add(articleStats);
        });

        if(!articleStatsList.isEmpty()){
            articleStatsService.saveOrUpdateBatch(articleStatsList);
        }
    }


}
